import http from 'wechat-http'

http.baseURL = 'https://live-api.itheima.net'


// 配置请求拦截器
http.intercept.request = function (options) {
  // 扩展头信息
  const defaultHeader = {}
  // 身份认证
  defaultHeader.Authorization = 'Bearer ' + getApp().token
  // 与默认头信息合并
  options.header = Object.assign({}, defaultHeader, options.header)
  // 处理后的请求参数
  return options
}

http.intercept.response = async function({data,config}){
  if(data.code==401){
    const app = getApp()
    const res = await http({
      url:'/refreshToken',
      method:'POST',
      header: {
        Authorization: 'Bearer ' + app.refreshToken,
      }
    })
    if(res.code!==10000){
      return wx.utils.toast('刷新token失败')
    }
    app.setToken('token',res.data.token)
    app.setToken('refreshToken',res.data.refreshToken)
    config = Object.assign(config,{
      header: {
        Authorization: 'Bearer ' + app.token
      }
    })
    return http(config)
  }
  return data
}

export default http